#!/usr/bin/env python3
import os
import sys
import re
from typing import List, Set
from typing import Optional,Union

# === 关键：将项目根目录加入 Python 路径 ===
current_dir = os.path.dirname(os.path.abspath(__file__))
roject_root = os.path.abspath(os.path.join(current_dir, ".."))
project_root = os.path.normpath(
    os.path.join(current_dir, "..")
)
if project_root not in sys.path:
    sys.path.insert(0, project_root)
from common import log_info, log_error, log_warn

# 静态类型关键词列表（可按需扩展）
SERVICE_KEYWORDS = ["BatchUpdate", "Campaign", "Project", "Report", "AdGroup", "Keyword", "Creative"]

def extract_media_name(field: str, keywords: List[str]) -> Union[str, None]:
    """
    从 field 中提取媒体前缀。
    规则：找到任意 keyword（忽略大小写）第一次出现的位置， 返回该位置之前的部分（即前缀）。
    如果没找到任何 keyword，返回 None。
    """
    field_lower = field.lower()
    min_pos = len(field)  # 初始化为末尾
    matched = False

    for kw in keywords:
        kw_lower = kw.lower()
        pos = field_lower.find(kw_lower)
        if pos != -1 and pos < min_pos:
            min_pos = pos
            matched = True

    if matched:
        return field[:min_pos]
    return None

def get_all_media_name(data_file: str) -> List[str]:
    """
    从数据文件中提取所有唯一的媒体前缀，并按字母顺序返回。
    Args   : data_file: 输入文件路径
    Returns: 排序后的媒体前缀列表
    Raises : SystemExit: 文件不存在或读取失败时退出程序
    """
    media_set: Set[str] = set()
    try:
        with open(data_file, 'r', encoding='utf-8') as f:
            for line in f:
                # ignore comment line
                if line.startswith("#"):
                    continue
                parts = line.split()
                if len(parts) < 2:
                    continue

                # filter column text
                for field in parts[1:]:
                    prefix = extract_media_name(field, SERVICE_KEYWORDS)
                    if prefix:
                        media_set.add(prefix.lower())

        return sorted(media_set)

    except FileNotFoundError:
        log_error(f"File '{data_file}' not found.")
        sys.exit(1)
    except Exception as e:
        log_error(f"Failed to read file: {e}")
        sys.exit(1)

def gen_all_media_table(data_file: str, media_name_list: List[str]) -> None:
    """
    生成逗号分隔的媒体支持表格（CSV 格式）。
    Args:
        data_file: 输入数据文件路径
        media_name_list: 媒体名称列表，决定输出列的顺序
    """
    # 构建媒体名称到列索引的映射（用于 O(1) 快速查找）
    media_to_index = {name: i for i, name in enumerate(media_name_list)}
    
    try:
        with open(data_file, 'r', encoding='utf-8') as f:
            for line in f:
                stripped_line = line.strip()
                # 跳过空行和注释行（以 # 开头）
                if not stripped_line or stripped_line.startswith("#"):
                    continue

                parts = stripped_line.split()
                if not parts:
                    continue

                api_type = parts[0]
                api_class_list = parts[1:]

                # 初始化输出行：[api_type, "", "", ..., ""]
                # 遍历当前行的所有 API 类名，尝试提取并匹配媒体名称
                output_cols = [api_type] + [""] * len(media_name_list)
                for api_class in api_class_list:
                    api_class_lower = api_class.lower()
                    for i, media in enumerate(media_name_list):
                        if api_class_lower.startswith(media.lower()):
                            output_cols[i + 1] = api_class
                            break

                # 输出 CSV 行（逗号分隔）
                print(",".join(output_cols))

    except FileNotFoundError:
        log_error(f"Input file not found: {data_file}")
        sys.exit(1)
    except Exception as e:
        log_error(f"Error processing file '{data_file}': {e}")
        sys.exit(1)

def main():
    if len(sys.argv) != 2:
        log_info("Usage: python3 api_media_generator.py <data_file>")
        sys.exit(1)

    # 打印标题行
    data_file = sys.argv[1]
    media_name_list = get_all_media_name(data_file)
    header = ["Operation"] + media_name_list
    print(",".join(header))

    # 打印数据行
    meida_table = gen_all_media_table(data_file, media_name_list)

if __name__ == '__main__':
    main()
